/***********************************************************
 * Author: 	Brandon McKune
 * E-Mail:	bmckune.cs@gmail.com
 * Date:	October 2, 2011
 * Class:	CSc 8370 - Data Security
 * Time:	1150 - 1325
 * Smstr:	Fall 2011
 */
#include "SimpleWorm.h"
#include "common.h"
#include <fcntl.h>
#include <unistd.h>


int main(int args0, char** args1){
	std::string sourceName = "../SimpleWorm.cpp";
	std::string binaryName = "SimpleWorm";
	static char myBuffer[2700] = {"enter"};

	int handle = open("SimpleWorm", O_RDWR);

	printf("Handle %d\n", handle);
	if(myBuffer[0] == 'e'){
		FILE *source = fopen(sourceName.c_str(), "r");
		FILE *binary = fopen(binaryName.c_str(), "r");
		FILE *newBinary = fopen("SimpleWorm.x", "w");

		uint64_t sourceSize;
		uint64_t binarySize;
		printf("Starting SimpleWorm.\n");

		if(source == NULL){
			fprintf(stderr, "Failure to load file: %s\n", sourceName.c_str());
			return -1;
		}
		if(binary == NULL){
			fprintf(stderr, "Failure to load file: %s\n", binaryName.c_str());
			return -1;
		}
		//Get the size of the file to create the internal buffer.
		fseek(source, 0, SEEK_END);
		sourceSize = ftell(source);
		rewind(source);

		printf("Source size: %d\n", sourceSize);

		fseek(binary, 0, SEEK_END);
		binarySize = ftell(binary);
		rewind(binary);

		char* binaryBuffer = (char*)malloc(binarySize);
		if(binaryBuffer == NULL){
			fprintf(stderr, "malloc() binary buffer failed.");
			return -1;
		}

		char* sourceBuffer = (char*)malloc(sourceSize);
		if(sourceBuffer == NULL){
			fprintf(stderr, "malloc() source buffer failed.");
			return -1;
		}

		uint64_t bytesRead = fread(binaryBuffer, BYTE, binarySize, binary);
		printf("I read %d bytes for binary\n", bytesRead);
		if(bytesRead != binarySize){
			fprintf(stderr, "fread binary failed.");
			return -1;
		}

		bytesRead = fread(sourceBuffer, BYTE, sourceSize, source);
		printf("I read %d bytes for source\n", bytesRead);
		if(bytesRead != sourceSize){
			fprintf(stderr, "fread source failed.");
			return -1;
		}

		uint64_t entryIndex = 0;

		for(uint64_t i = 0; i < binarySize; i++){
			if(binaryBuffer[i] == 'e' &&
				binaryBuffer[i+1] == 'n' &&
				binaryBuffer[i+2] == 't' &&
				binaryBuffer[i+3] == 'e' &&
				binaryBuffer[i+4] == 'r'){
				printf("Found my string.\n");
				entryIndex = i;
			}
		}

		for(uint64_t i = 0; i < sourceSize; i++){
			binaryBuffer[entryIndex + i] = sourceBuffer[i];
		}

		fwrite(binaryBuffer, BYTE, binarySize, newBinary);
		system("mv SimpleWorm.x SimpleWorm; chmod 777 SimpleWorm");
		fclose(source);
		fclose(binary);
	}else{
		printf("This is my buffer:\n%s\n", myBuffer);
	}


	return 0;
}
